#include "BlogItemWidget.h"

BlogItemWidget::BlogItemWidget(
    QWidget *parent,
    const QString &title,
    const QString &summary,
    const QPixmap &cover)
    : QWidget(parent),
      titleLabel(new QLabel(title, this)),
      summaryLabel(new QLabel(summary, this)),
      coverLabel(new QLabel(this)),
      mainLayout(new QHBoxLayout(this)),
      textLayout(new QVBoxLayout())
{
    this->setStyleSheet(
        "QWidget {"
        "border: 1px solid #ccc;"
        "border-radius: 8px;"
        "background-color: #EEEEEE;"
        "}");

    coverLabel->setPixmap(cover.scaled(CoverWidth, CoverHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
    coverLabel->setAlignment(Qt::AlignCenter);                         // 居中对齐
    coverLabel->setFixedSize(CoverWidth, CoverHeight);                 // 固定宽高
    coverLabel->setScaledContents(false);                              // 禁止自动缩放内容
    coverLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // 固定大小

    summaryLabel->setWordWrap(true);                                         // 自动换行
    summaryLabel->setFixedHeight(60);                                        // 设置固定高度
    summaryLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); // 固定高度

    // 右侧文本区域
    textLayout->addWidget(titleLabel);   // 标题
    textLayout->addWidget(summaryLabel); // 摘要

    // 设置摘要自动换行
    summaryLabel->setWordWrap(true);
    summaryLabel->setAlignment(Qt::AlignTop);
    summaryLabel->setMaximumHeight(60);

    titleLabel->setStyleSheet(
        "font-size: 16px;"
        "font-weight: bold;");

    summaryLabel->setStyleSheet(
        "color: #888;");

    // 主布局：封面 + 文本区
    mainLayout->addWidget(coverLabel); // 左侧封面
    mainLayout->addLayout(textLayout); // 右侧内容
    // 设置拉伸因子，让 textLayout 占据剩余空间
    mainLayout->setStretch(0, 0); // 封面不拉伸
    mainLayout->setStretch(1, 1); // 文字区域拉伸填充
    setLayout(mainLayout);

    this->setCursor(Qt::PointingHandCursor); // 鼠标悬停时显示手型光标
}

void BlogItemWidget::setTitle(const QString &title)
{
    titleLabel->setText(title);
}

void BlogItemWidget::setSummary(const QString &summary)
{
    summaryLabel->setText(summary);
}

void BlogItemWidget::setCover(const QPixmap &cover)
{
    coverLabel->setPixmap(cover.scaled(CoverWidth, CoverHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
}

void BlogItemWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        emit openDetailPage(); // 发出跳转信号
        qDebug() << "跳转至文章详情";
    }
    QWidget::mousePressEvent(event);
}

void BlogItemWidget::quickSetup(const BlogPreview &blogPreview)
{
    titleLabel->setText(blogPreview.title);
    summaryLabel->setText(blogPreview.summary);
    coverLabel->setPixmap(blogPreview.cover.scaled(CoverWidth, CoverHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
}